package com.wpw.dream.spider.init;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.wpw.dream.spider.entity.SpiderConfig;
import com.wpw.dream.spider.enums.SpiderRunStatusEnum;
import com.wpw.dream.spider.enums.SpiderTypeEnum;
import com.wpw.dream.spider.service.SpiderService;

public class SpiderInit {
	
	
	@Autowired
	private SpiderService spiderService;
	
	public void init() throws InterruptedException {
		
		//ExecutorService pool = Executors.newFixedThreadPool(5);
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				boolean flag = false;
				while (true) {
					List<SpiderConfig> list;
					if (flag) {
						list = spiderService.findAll();
					} else {
						list = spiderService.findAllCache();
					}
					List<Long> spiderIds = new ArrayList<>();
					Long currentTime = System.currentTimeMillis();
					int count = 0;
					for (SpiderConfig spiderConfig : list) {
						if (SpiderRunStatusEnum.STOP.getValue().equals(spiderConfig.getRunStatus())) {
							if (SpiderTypeEnum.EVERY_HOURS.getValue().equals(spiderConfig.getSpiderType())) {
								Long lastRuntime = spiderConfig.getLastRuntime();
								if (lastRuntime == 0) {
									flag = true;
								} else {
									count ++;
								}
								Integer spiderTime = Integer.parseInt(spiderConfig.getSpiderTime());
								if (currentTime - lastRuntime > 1000L*60*60*spiderTime) {
									spiderIds.add(spiderConfig.getId());
								}
							}
						}
						
					}
					
					if (list != null && count == list.size()) {
						flag = false;
					}
					
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					if (CollectionUtils.isNotEmpty(spiderIds)) {
						spiderService.doSpider(spiderIds);
					}
					
				}
				
			}
		}).start();;
		
	}
}
